package cn.iocoder.yudao.module.reading.service.book;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.reading.controller.admin.book.vo.PictureBookCreateReqVO;
import cn.iocoder.yudao.module.reading.controller.admin.book.vo.PictureBookPageReqVO;
import cn.iocoder.yudao.module.reading.controller.admin.book.vo.PictureBookUpdateReqVO;
import cn.iocoder.yudao.module.reading.dal.dataobject.book.PictureBookDO;
import cn.iocoder.yudao.module.reading.dal.mysql.book.PictureBookMapper;
import cn.iocoder.yudao.module.reading.dal.mysql.book.BookPageMapper;
import cn.iocoder.yudao.module.reading.framework.util.StaticResourceUrlUtils;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.module.reading.enums.ErrorCodeConstants.PICTURE_BOOK_NOT_EXISTS;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 管理员绘本 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class AdminPictureBookServiceImpl implements AdminPictureBookService {

    @Resource
    private PictureBookMapper pictureBookMapper;

    @Resource
    private BookPageMapper bookPageMapper;

    @Resource
    private StaticResourceUrlUtils staticResourceUrlUtils;

    @Override
    public Long createPictureBook(PictureBookCreateReqVO createReqVO) {
        // 转换为DO对象
        PictureBookDO book = BeanUtils.toBean(createReqVO, PictureBookDO.class);
        book.setPages(0); // 初始页面数量为0

        // 处理封面URL：将完整URL转换为相对路径存储
        if (StrUtil.isNotEmpty(book.getCover())) {
            String relativePath = staticResourceUrlUtils.toRelativePath(book.getCover());
            book.setCover(relativePath);
            log.debug("绘本封面URL标准化: {} -> {}", createReqVO.getCover(), relativePath);
        }

        // 插入数据库
        pictureBookMapper.insert(book);

        log.info("绘本创建成功，ID: {}, 标题: {}", book.getId(), book.getTitle());
        return book.getId();
    }

    @Override
    public void updatePictureBook(PictureBookUpdateReqVO updateReqVO) {
        // 校验存在
        validatePictureBookExists(updateReqVO.getId());

        // 转换为DO对象
        PictureBookDO updateObj = BeanUtils.toBean(updateReqVO, PictureBookDO.class);

        // 处理封面URL：将完整URL转换为相对路径存储
        if (StrUtil.isNotEmpty(updateObj.getCover())) {
            String relativePath = staticResourceUrlUtils.toRelativePath(updateObj.getCover());
            updateObj.setCover(relativePath);
            log.debug("绘本封面URL标准化: {} -> {}", updateReqVO.getCover(), relativePath);
        }

        // 更新数据库
        pictureBookMapper.updateById(updateObj);

        log.info("绘本更新成功，ID: {}", updateReqVO.getId());
    }

    @Override
    public void deletePictureBook(Long id) {
        // 校验存在
        validatePictureBookExists(id);

        // 删除绘本
        pictureBookMapper.deleteById(id);

        log.info("绘本删除成功，ID: {}", id);
    }

    @Override
    public PictureBookDO getPictureBook(Long id) {
        PictureBookDO book = pictureBookMapper.selectById(id);
        if (book == null) {
            throw exception(PICTURE_BOOK_NOT_EXISTS);
        }
        return book;
    }

    @Override
    public PageResult<PictureBookDO> getPictureBookPage(PictureBookPageReqVO pageReqVO) {
        return pictureBookMapper.selectPage(pageReqVO);
    }

    @Override
    public List<PictureBookDO> getPictureBooksByBookSetId(Long bookSetId) {
        return pictureBookMapper.selectByBookSetId(bookSetId);
    }

    @Override
    public List<Long> batchCreatePictureBooks(List<PictureBookCreateReqVO> createReqVOs) {
        List<Long> bookIds = new ArrayList<>();
        
        for (PictureBookCreateReqVO createReqVO : createReqVOs) {
            Long bookId = createPictureBook(createReqVO);
            bookIds.add(bookId);
        }
        
        log.info("批量创建绘本成功，数量: {}", bookIds.size());
        return bookIds;
    }

    @Override
    public Long getNextPictureBookId() {
        // 获取当前最大ID
        Long maxId = pictureBookMapper.selectMaxId();
        // 计算下一个ID（如果表为空，从1开始）
        Long nextId = (maxId == null ? 0 : maxId) + 1;

        log.info("获取下一个绘本ID: {}", nextId);
        return nextId;
    }

    @Override
    public synchronized List<Long> getBatchNextPictureBookIds(int count) {
        if (count <= 0) {
            throw new IllegalArgumentException("获取ID数量必须大于0");
        }

        // 获取当前最大ID
        Long maxId = pictureBookMapper.selectMaxId();
        Long startId = (maxId == null ? 0 : maxId) + 1;

        // 生成连续的ID列表
        List<Long> idList = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            idList.add(startId + i);
        }

        log.info("批量获取绘本ID成功，起始ID: {}, 数量: {}, ID列表: {}", startId, count, idList);
        return idList;
    }

    @Override
    public void updateBookPageCount(Long bookId) {
        // 校验绘本是否存在
        validatePictureBookExists(bookId);

        // 统计该绘本的页面数量
        int pageCount = bookPageMapper.selectByBookId(bookId).size();

        // 更新绘本的页面数量
        PictureBookDO updateObj = new PictureBookDO();
        updateObj.setId(bookId);
        updateObj.setPages(pageCount);
        pictureBookMapper.updateById(updateObj);

        log.info("更新绘本页面数量成功，绘本ID: {}, 页面数量: {}", bookId, pageCount);
    }

    @Override
    public void batchUpdateBookPageCount(List<Long> bookIds) {
        if (bookIds == null || bookIds.isEmpty()) {
            return;
        }

        for (Long bookId : bookIds) {
            updateBookPageCount(bookId);
        }

        log.info("批量更新绘本页面数量成功，绘本数量: {}", bookIds.size());
    }

    @Override
    public List<PictureBookDO> getPictureBookList(Long bookSetId, String title) {
        return pictureBookMapper.selectList(bookSetId, title);
    }

    /**
     * 校验绘本是否存在
     */
    private void validatePictureBookExists(Long id) {
        if (pictureBookMapper.selectById(id) == null) {
            throw exception(PICTURE_BOOK_NOT_EXISTS);
        }
    }

}
